<template>
  <div class="content">
    <div class="top_btn">
      <a-button type="primary" class="bd-r" @click="goback">返回</a-button>
    </div>

    <div class="content_box">
      <div class="contemt_left">
        <div class="content_left_top">
          <a-form layout="vertical">
            <a-form-item label="爆店码活动名称" v-bind="validateInfos.name">
              <a-input
                v-model:value="modelRef.name"
                placeholder="请输入爆店码活动名称"
                allowClear
                show-count
                :maxlength="60"
              />
            </a-form-item>

            <!-- <a-form-item label="活动扫码海报" v-bind="validateInfos.Poster">
              <div class="info_text">
                图片像素建议750*1334像素,格式为jpg,jpeg和png, 大小不超过2M
              </div>

              <div class="up_box">
                <a-upload
                  v-model:file-list="fileList"
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :multiple="false"
                  :show-upload-list="false"
                  :customRequest="customRequest"
                  :accept="'.jpg,.jpeg,.png'"
                  :before-upload="beforeUpload"
                >
                  <img
                    v-if="modelRef.poster"
                    class="img_haibao"
                    :src="modelRef.poster"
                    alt="avatar"
                  />
                  <div v-else>
                    <loading-outlined v-if="loading"></loading-outlined>
                    <plus-outlined v-else></plus-outlined>
                  </div>
                </a-upload>

                <a-button class="Rup_btn"  @click="RestoreFn">恢复初始</a-button>

                <div class="example" v-if="up_ing">
                  <a-spin tip="Loading..." />
                </div>
              </div>
            </a-form-item> -->

            <a-form-item label="活动截止日期" v-bind="validateInfos.end_time">
              <a-date-picker
                v-model:value="modelRef.end_time"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm"
                :show-time="{ defaultValue: dayjs('00:00', 'HH:mm') }"
                :showNow="false"
                :disabledDate="disabledDate"
                :disabled-time="disabledTime"
                 @change="handleTimeChange"
              />
            </a-form-item>
          </a-form>
        </div>

        <div class="content_left_bottom">
          <a-form layout="vertical">
            <a-form-item v-bind="validateInfos.intoPieces" :colon="false">
              <template #label>
                <span class="custom-label"> 营销视频 
                   <span
                  style="
                    height: 100%;
                    border-radius: 5px;
                    margin-right: 3px;
                    background-color: var(--ss-primary-color);
                    color: #fff;
                    padding: 0 5px;
                    margin-left: 5px;
                  "
                  >{{ filmVideoList.length }}</span
                >
                </span>
                
                
                <span style="margin-left: 18px">
                  添加多个营销视频时, 每次随机分配一个
                </span>
              </template>
              <!-- 成片列表 -->
              <div class="movieslist">
                <!-- 添加成片 -->
                <div class="movies_add" @click="intoPiecesClick">
                  <plus-outlined style="font-size: 16px" />
                  <div style="margin-top: 5px">选择成片</div>
                </div>
                <!-- 单个成片 -->
                <div
                  class="movies_item"
                  v-for="(item, index) in filmVideoList"
                  :key="item.id"
                >
                  <img
                    v-if="item?.image_ary"
                    :src="item?.image_ary[0]"
                    alt=""
                  />
                  <img
                    v-if="item.cover_url && item.cover_url !== ''"
                    :src="item.cover_url"
                    alt=""
                    style="width: 100%; height: 100%"
                  />

                  <video
                    v-if="!item.cover_url && !item?.image_ary"
                    :src="item.material_url"
                    style="width: 100px; height: 100px"
                  ></video>
                  <!-- 持续时长 -->
                  <span class="movies_duration">{{
                    durationTime(item.material_duration)
                  }}</span>

                  <div class="movies_itemmask" @click.stop="previewImg(item)">
                    <cu-icon
                      class="play_icon"
                      type="icon-shipin"
                      style="font-size: 24px"
                    />
                    <!-- 关闭按钮 -->
                    <span
                      class="movies_closebtn"
                      @click.stop="deleteFilmVideo(index)"
                      ><delete-outlined
                    /></span>
                  </div>
                </div>
              </div>
            </a-form-item>
          </a-form>

          <!-- 视频描述 -->
          <div class="title_tip">
            <div style="display: flex; align-items: center">
              <span style="margin-right: 8px"
                >视频描述
                <span
                  style="
                    height: 100%;
                    border-radius: 5px;
                    margin-right: 3px;
                    background-color: var(--ss-primary-color);
                    color: #fff;
                    padding: 0 5px;
                    margin-left: 5px;
                  "
                  >{{ titleList.length }}</span
                >
              </span>

              <span style="margin-left: 20px">
                添加多个描述时, 每次随机分配一个描述
              </span>

              <span
                v-if="AILoading"
                style="font-size: 14px; flex: 1; margin: 0 15px"
                >预计生成：<span style="font-weight: 600">{{
                  AIExpanSionTotal
                }}</span
                >，已生成：<span style="font-weight: 600">{{
                  AIExpanSionCount
                }}</span></span
              >
              <a-progress
                size="small"
                v-if="AILoading"
                :percent="AIExpansionPercent"
                style="width: 140px"
              />
            </div>
            <a-popover v-if="AILoading">
              <template #content> AI扩写生产中，请耐心等待 </template>
              <a-button
                disabled
                class="ai_disabled"
                size="small"
                style="display: flex !important; align-items: center"
              >
                <template #icon>
                  <cu-icon
                    type="icon-AIxiezuozhushou"
                    style="color: #2580fd; font-size: 18px; margin-top: 3px"
                  ></cu-icon>
                </template>
                AI扩写
              </a-button>
            </a-popover>
            <!-- <a-button
              v-else
              size="small"
              @click="addAIExpansion"
              style="display: flex; align-items: center"
            >
              <template #icon>
                <cu-icon
                  type="icon-AIxiezuozhushou"
                  style="color: #2580fd; font-size: 18px; margin-top: 3px"
                ></cu-icon>
              </template>
              AI扩写
            </a-button> -->
          </div>
          <!-- 标题展示列表  -->
          <div
            class="title_list_more"
            style="margin-top: 8px"
           v-if="titleList.length > 0"
          >
            <div
              class="title-item"
              v-for="(item, index) in titleList"
              :key="index"
            >
              <div class="item-text" v-if="item.text">
                <span style="font-weight: 600">标题：</span>{{ item.text }}
              </div>
              <div class="item-caption"  @click="addTitleHandle('view')">
                <span class="caption">{{ item?.caption }}</span>
               
                <a-space class="operation"
                  ><edit-outlined
                    class="edit_btn"
                    /><delete-outlined
                    class="delete_btn"
                    v-if="titleList.length > 1"
                    @click="deleteTitle"
                /></a-space>
              </div>
              <div
                class="hashtag_name"
                v-if="
                  PlatFormValue != 'kuaishou' && item?.hashtag_name.length > 0
                "
              >
                <a-tag
                  v-for="(name, i) in item.hashtag_name"
                  :key="i"
                  style="background: #d5e3f4; font-size: 10px"
                >
                  <template v-if="PlatFormValue != 'xiaohongshu'">
                    #{{ name }}
                  </template>

                  <template v-else> #{{ name.value }} </template>
                </a-tag>
              </div>
            </div>
          </div>
          <!-- 添加视频描述按钮 -->
          <a-button
            :disabled="AILoading"
            style="margin: 10px 0"
            block
            type="dashed"
            @click="addTitleHandle('add')"
            ><plus-outlined />添加视频描述</a-button
          >
          <!-- 挂载内容提示标题 -->
          <div class="title_tip">
            <span
              >挂载内容
              <a-tooltip>
                <template #title>{{ contentTip }}</template>
                <question-circle-outlined style="margin-left: 3px" />
              </a-tooltip>
              <span
                v-if="modelRef.anchor_type == 2"
                style="color: #2878ff; cursor: pointer; margin-left: 5px"
                @click.stop="requirementsClick"
              >
                查看挂载要求
              </span></span
            >
            <!-- 挂载内容-位置数量 -->
            <!-- <span
              @click="addPoiHandle"
              v-if="modelRef.anchor_type == 1 && poiList.length > 0"
              ><span class="see_posion">{{ poiList.length }}</span
              >查看位置<right-outlined class="fz12"
            /></span> -->
            <!-- 挂载内容-小程序数量 -->
            <span
              @click="addMobilHandle"
              v-if="modelRef.anchor_type == 2 && mobileList.length > 0"
              ><span class="see_posion">{{ mobileList.length }}</span
              >查看小程序<right-outlined class="fz12"
            /></span>
            <!-- 挂载内容-小黄车数量 -->
            <span
              @click="viewSmallCart"
              v-if="modelRef.anchor_type == 3 && shop_cart.length > 0"
              ><span class="see_posion">{{ hasAddCartCountCount }}</span
              >查看小黄车挂载<right-outlined class="fz12"
            /></span>
          </div>

          <a-form layout="vertical" style="margin-top: 10px">
            <!-- 挂载内容左侧选择框 -->
            <a-form-item
              :colon="false"
              v-bind="validateInfos.anchor_type"
              style="width: 100%; margin-bottom: 10px !important"
            >
              <a-select
                v-model:value="modelRef.anchor_type"
                :placeholder="
                  PlatFormValue == 'xiaohongshu' && !accountList?.length
                    ? '请先选择账号'
                    : '请选择挂载内容'
                "
                style="width: 100%"
                :style="{
                  border: borderErrStyle ? '2px solid red !important' : '',
                }"
                @change="antchor_typeChange"
              >
                <a-select-option
                  v-for="item in anchorTypeListComputed"
                  :disabled="item.disabled"
                  :value="item.value"
                  :key="item.value"
                >
                  <a-tooltip placement="top">
                    <template #title>
                      <span>{{ item?.tip || "" }}</span>
                    </template>
                    <template v-if="item.disabled">
                      <div>{{ item.label }}</div>
                    </template>
                  </a-tooltip>
                  <span v-if="!item.disabled">{{ item.label }}</span>
                </a-select-option>
              </a-select>
            </a-form-item>
            <!-- 添加位置按钮 -->
            <a-button
              block
              v-if="modelRef.anchor_type == 1"
              type="dashed"
              style="margin-bottom: 10px"
              @click="addPoiHandle"
              ><plus-outlined />添加位置</a-button
            >

            <!-- 添加小程序按钮 -->
            <a-button
              block
              type="dashed"
              v-if="modelRef.anchor_type == 2"
              style="margin-bottom: 10px"
              @click="addMobilHandle"
              ><plus-outlined />添加小程序</a-button
            >
            <a-button
              block
              type="dashed"
              v-if="modelRef.anchor_type == 3"
              style="margin-bottom: 10px"
              @click="addSmallCartHandle"
              :loading="addYellowCartLoading"
              ><plus-outlined />添加小黄车</a-button
            >
          </a-form>

          <div class="position_box">
            <div
              class="position_box_item"
              v-for="(item, index) in poiList"
              :key="index"
            >
              {{ item.store_name }}
              <close-outlined
                class="del_icon"
                @click="deletePoiList(item.id)"
              />
            </div>
          </div>

          <div class="bottom_btn">
            <!-- <a-button class="bd-r" @click="goback"> 取消 </a-button> -->
            <a-button
              style="width: 80px; margin-top: 20px"
              type="primary"
              class="bd-r"
              @click="debouncedsubmitFn"
            >
              提交
              <!-- <div v-if="activity_id > 0">编辑爆店码</div>
            <div v-else>添加爆店码</div> -->
            </a-button>
          </div>
        </div>
      </div>

      <!-- 右侧手机组件 -->
      <!-- <div class="contemt_right">
        <div class="top_content">
          <div
            class="phone"
            :style="{
              backgroundImage: `url(${phonebg})`,
              backgroundSize: 'cover',
            }"
          >
            <div class="one_content">
              <div class="top_header">
                <div class="left"><close-outlined /></div>
                <div class="right">活动扫码海报</div>
              </div>
              <div
                class="content_img"
                :style="{
                  backgroundImage: `url(${modelRef.poster})`,
                  backgroundSize: 'cover',
                  backgroundPosition: 'center',
                  backgroundRepeat: 'no-repeat',
                }"
              >
                <DraggableContainer
                  :style="{
                    width: '226px',
                    height: '368px',
                  }"
                  :referenceLineColor="'transparent'"
                >
                  <Vue3DraggableResizable
                    style="padding: 0; z-index: 999"
                    v-model:x="editSubtitleItem.x"
                    v-model:y="editSubtitleItem.y"
                    :w="ResizableWidth"
                    :h="Resizableheight"
                    v-model:active="ResizableActive"
                    :key="editSubtitleItem.subtitle_id"
                    :lockAspectRatio="true"
                    :resizable="true"
                    :draggable="true"
                    :parent="true"
                    @drag-end="dragEndHandle"
                  >
                    <img class="content_code" :src="codeimg" alt="" />
                  </Vue3DraggableResizable>
                </DraggableContainer>
              </div>
            </div>
          </div>

          <div
            class="phone"
            :style="{
              backgroundImage: `url(${phonebg})`,
              backgroundSize: 'cover',
            }"
          ></div>
        </div>

       
      </div> -->
    </div>

    <!-- 添加成片组件 -->
    <CloudImageLibrary
      :film_type="modelRef.film_type"
      :film_platform="modelRef.platform"
      :visible="imageLibraryVisible"
      :filmVideoIds="filmVideoIds"
      :selectVideoList="selectVideoList"
      :new_filmVideoList ="filmVideoList"
      :poiKey="poiKey"
      :libraryList="libraryList"
      :editingList="editingList"
      @onCancel="imageLibraryVisible = false"
      @onConfirm="onConfirmChange"
    />

    <!-- AI扩写 -->
    <AIExpansion ref="aiExpansionRef" @onConfirm="onConfirmAIExpansion" />

    <!-- 添加标题 -->
    <addTitleDrawer
      ref="addTitledrawer"
      :PlatFormValue="PlatFormValue"
      @success="addTitleSuccess"
      :title_list="titleList"
      :ismiaoshu="true"
      :accountList="accountList || []"
    />
    <!-- 添加位置 -->
    <addPoiList
      ref="addpoilist"
      @deletePoiList="deletePoiList"
      :poiList="poiList"
      @addPoiList="storePOI"
      @success="addPoiSuccess"
    />

    <!-- 选择门店POI -->
    <StorePOI
      :visible="visibleStorePOI"
      :poiId="poiId"
      @onCancel="visibleStorePOI = false"
      @onConfirm="onConfirmStorePOI"
    />

    <!-- 预览 -->
    <PreviewModal
      :visible="visibleImage"
      @onCancel="visibleImage = false"
      :url="previewImgUrl"
      :title="previewTitle"
      :type="typeChange"
    />
  </div>
</template>

<script setup>
import {
  computed,
  defineComponent,
  ref,
  reactive,
  watch,
  createVNode,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  PlusOutlined,
  LoadingOutlined,
  EditOutlined,
  QuestionCircleOutlined,
  CloseOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import CloudImageLibrary from "@/views/shotstack/MatrixMarketing/modules/CloudImageLibrary.vue";
import request from "../../../common/utils/request";
import AIExpansion from "@/views/shotstack/MatrixMarketing/modules/AIExpansion.vue";
// 添加标题组件
import addTitleDrawer from "@/views/shotstack/MatrixMarketing/modules/addTitleDrawer.vue";
// 添加位置组件
import addPoiList from "@/views/shotstack/MatrixMarketing/modules/addPoiList.vue";
import StorePOI from "@/views/shotstack/MatrixMarketing/modules/StorePOI.vue";
import PreviewModal from "@/components/PreviewModal/index.vue";
import { debounce } from "lodash";

// 手机组件
import { DraggableContainer } from "vue3-draggable-resizable";
import Vue3DraggableResizable from "vue3-draggable-resizable";
import "vue3-draggable-resizable/dist/Vue3DraggableResizable.css";
import { upload } from "@/common/utils/uploader/index";
import { Modal } from "ant-design-vue";
import dayjs from "dayjs";

import { Form, message } from "ant-design-vue";
import PoiListAddPol from "../MaterialCenter/modules/PoiListAddPol.vue";
const router = useRouter();
const route = useRoute();
const useForm = Form.useForm;

const poiKey = ref(0);

const PlatFormValue = ref("douyin");

const modelRef = ref({
  name: "",
  film_type: 1,
  platform: "douyin",
  anchor_type: 0,
  start_time: "",
  end_time: "",
  intoPieces: [],
  // poster: "",
});
const rulesRef = ref({
  name: [
    {
      required: true,
      message: "请输入爆店码活动名称",
    },
  ],
  end_time: [
    {
      required: true,
      message: "请选择活动有效期",
    },
  ],
  // Poster: [
  //   {
  //     required: true,
  //     message: "请上传活动扫码海报",
  //   },
  // ],
  intoPieces: [
    {
      required: true,
      message: "请添加成片",
    },
  ],
  anchor_type: [
   {
      required: true,
      message: "请选择位置",
    },
  ]
});

const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);

const goback = () => {
  router.go(-1);
};


const disabledDate = (current) => {
  return current && current < dayjs().startOf("day");
};

const disabledTime = (time) => {
  const currentTime = dayjs();
  const today = currentTime.startOf('day');
  const targetTime = currentTime.add(30, "minute");

  // 动态生成禁用的小时列表
  const disabledHours = () => {
    return Array.from({ length: 24 }, (_, i) => i)
      .filter(hour => currentTime.hour(hour).isBefore(targetTime));
  };

  // 动态生成禁用的分钟列表（仅当选择了当前小时内）
  const disabledMinutes = (selectedHour) => {
    if (selectedHour === currentTime.hour()) {
      return Array.from({ length: 60 }, (_, i) => i)
        .filter(minute => currentTime.hour(selectedHour).minute(minute).isBefore(targetTime));
    }
    return [];
  };

  // 如果 time 为 null 或者选择的是今天的日期，则应用禁用逻辑
  if (!time || dayjs(time).isSame(today, 'day')) {
    return {
      disabledHours,
      disabledMinutes: (hour) => disabledMinutes(hour),
      disabledSeconds: () => [],
    };
  }

  // 对于其他情况（如选择了未来的日期），不做任何禁用处理
  return {
    disabledHours: () => [],
    disabledMinutes: () => [],
    disabledSeconds: () => [],
  };
};



const accountList = ref([]);

const is_Douyin_type = ref("api");

// 判断是否是抖音扫码发布
const douyinQrcode = computed(() => {
  const flage =
    is_Douyin_type.value == "qr_code" && PlatFormValue.value == "douyin";
  return flage;
});

// 上传前的准备
const beforeUpload = async (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  let w = 0,
    h = 0;
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    const image = new Image();
    image.src = reader.result;
    image.onload = () => {
      w = image.width;
      h = image.height;
      if (w <= 49 || h <= 49) {
        state.fileList = state.fileList.filter((item) => item.uid !== file.uid);
        message.error("图片宽度不能小于50px");
        return false;
      } else if (w >= 8000 || h >= 8000) {
        state.fileList = state.fileList.filter((item) => item.uid !== file.uid);
        message.error("图片宽度不能大于8000px");
        return false;
      }
      if (!isLt2M) {
        message.error("文件不可大于 2M!");
        return false;
      }
      return true;
    };
  };
};

const oss_config = ref({});
const imageUrl = ref(
  "https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/shotstack/20241112/t9kuWMhcuRjEaqgKvv5JV.jpg"
);
async function getOss_config() {
  const response = await request.post(
    "/work_ai",
    "/upload/oss/config/ststoken"
  );
  if (response.sts) {
    oss_config.value = response.sts;
  } else {
    const Reres = await request.post(
      "/work_ai",
      "/upload/oss/config/ststoken",
      {
        isRefresh: "1",
      }
    );
    oss_config.value = Reres.sts;
  }
}

const up_ing = ref(false);
const customRequest = async (file) => {
  let mu_file = file.file;
  await getOss_config();

  // 可选的配置对象
  const config = {
    SetUploadPath: "",
    oss_config: oss_config.value,
  };
  up_ing.value = true;
  const res = await upload(mu_file, config);
  if (res && res.fileUrl) {
    message.success("海报上传成功!");
    modelRef.value.poster = res.fileUrl;
    up_ing.value = false;
  }
};

const imageLibraryVisible = ref(false);

const selectVideoList = ref([]);
const poiList = ref([]);

const filmVideoIds = ref([]);
const filmVideoList = ref([]);

// 打开添加成片抽屉
const intoPiecesClick = () => {
  // 如果有门店的情况下
  if (poiKey.value) {
    let videoList = [];
    poiList.value.forEach((item) => {
      if (item.video_list) {
        videoList.push({
          video_list: item.video_list,
          store_id: item.store_id,
        });
      }
    });
    selectVideoList.value = videoList;
    imageLibraryVisible.value = true;
    return;
  }
  filmVideoIds.value = filmVideoList.value.map((item) => item.id);
  imageLibraryVisible.value = true;
};

// 添加成片
const onConfirmChange = (list) => {
  if (poiKey.value) {
    // 为每个门店单独存放一个成片数组字段 保存的时候用
    poiList.value.forEach((item) => {
      if (poiKey.value == item.id) {
        //选中 checked为true的
        filmVideoList.value = filmVideoList.value.concat(
          list.filter((i) => i.checked)
        );
        //取消弹框选中后的传给父组件处理当时已经选择的checkd为false
        filmVideoList.value.forEach((film) => {
          list.forEach((v) => {
            if (!v.checked && v.id == film.id) {
              film.checked = false;
            }
          });
        });
        // 处理筛选列表为true的
        filmVideoList.value = filmVideoList.value.filter(
          (film) => film.checked
        );

        item.store_id = item.id;
        item.video_list = filmVideoList.value;
        item.videoListLength = filmVideoList.value.length;
        item.video_ids = item.video_list.map((video) => video.id);
        item.video_ids = [...new Set(item.video_ids)];
      }
    });
    modelRef.value.intoPieces = filmVideoList.value;
    imageLibraryVisible.value = false;
    return;
  }
const seenIds = new Set();
  filmVideoList.value = list.filter(item => {
  if (!seenIds.has(item.id)) {
    seenIds.add(item.id);
    return true;
  }
  return false;
});
  imageLibraryVisible.value = false;
  modelRef.value.intoPieces = filmVideoList.value;
};

// 视频持续时长
const durationTime = (e) => {
  const totalSeconds = Math.floor(e / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;

  const paddedMinutes = String(minutes).padStart(2, "0");
  const paddedSeconds = String(seconds).padStart(2, "0");

  return `${paddedMinutes}:${paddedSeconds}`;
};

const swiperVisible = ref(false);
const imageArr = ref([]);
const previewImgUrl = ref("");
const typeChange = ref("video");
const previewTitle = ref("");
const visibleImage = ref(false);
// 查看视频
const previewImg = (data) => {
  if (data?.image_ary && data?.image_ary?.length) {
    swiperVisible.value = true;
    imageArr.value = data?.image_ary;
    return;
  }
  previewImgUrl.value = data.material_url;
  typeChange.value = data.material_type;
  previewTitle.value = data.material_name;
  visibleImage.value = true;
};

// 删除成片
const deleteFilmVideo = (index) => {
  Modal.confirm({
    title: "删除成片",
    icon: createVNode(ExclamationCircleOutlined),
    content: "确定删除成片吗？",
    cancelText: "取消",
    okText: "确定",
    onOk() {
      filmVideoList.value = filmVideoList.value.filter(
        (item, Vindex) => Vindex !== index
      );
      poiList.value.forEach((item) => {
        if (item.store_id == poiKey.value) {
          item.video_list = filmVideoList.value;
          item.video_ids = item.video_list.map((video) => video.id);
          item.videoListLength = filmVideoList.value.length;
        }
      });
      if (!filmVideoList.value.length) {
        modelRef.value.intoPieces = [];
      }
      message.success("删除成功");
    },
    onCancel() {},
  });
};
// 有成片的混剪列表
const editingList = ref([]);
const libraryList = ref([]);
const fetching = ref(false);
const getEditingList = async () => {
  const res = await request.get("/work_ai", "/user/shotstack/editing/list");
  editingList.value = res.result.map((item) => {
    return {
      label: item.title,
      value: item.id,
    };
  });
};
getEditingList();

// 获取项目列表
const getLibraryList = () => {
  fetching.value = true;
  request
    .get("/work_ai", "/user/shotstack/library/withGroup/list")
    .then((res) => {
      libraryList.value = res.result.map((item) => {
        return {
          label: item.name,
          value: item.id,
          default: item.default_group_id,
        };
      });
      fetching.value = false;
    });
};
getLibraryList();

const titleList = ref([]);
const activity_id = ref(0);

const contentTip = computed(() => {
  switch (modelRef.value.anchor_type) {
    case 0:
      return "发布后携带的内容";
    case 1:
      return "发布后成片将携带门店添加的POI地址信息";
    case 2:
      return "发布后成片将携带抖音小程序链接";
    case 3:
      return "仅支持抖音账号开通小黄车功能挂载商品";
    default:
      break;
  }
});

const phonebg = ref(
  "https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/shotstack/20241210/08uAJjRdSFIVEOkJIpDiG.png"
);

const codeimg = ref(
  "https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/shotstack/20241211/CDuvOtiHuFBzzZLcGcIhR.png"
);
// AI扩写
const aiExpansionRef = ref(null);
const AILoading = computed(() => {
  return aiExpansionRef.value && aiExpansionRef.value.AILoading;
});
const addAIExpansion = () => {
  aiExpansionRef.value && aiExpansionRef.value.showModal();
};
const onConfirmAIExpansion = (arr) => {
  aiExpansionRef.value && aiExpansionRef.value.cancelClick();
  if (arr) {
    titleList.value = [];

    console.log(arr,   '传出来的数组11111');
    arr.map((item) => {
      titleList.value.push({
        title: `标题${titleList.value.length + 1}`,
        key: titleList.value.length + 1,
        text: "",
        caption: item.text, //作品简介
        hashtag_name: item.hashtag_name,
        isSpining: false,
        ai_keyword_group_id: item.ai_keyword_group_id,
        ai_keyword_id: item.ai_keyword_id,
        keyWordsGroupList: item.keyWordsGroupList,
        keyWordsList: item.keyWordsList,
      });
    });
  }
};

// 添加标题
const addTitledrawer = ref(null);
const addTitleHandle = (openType) => {
  if (AILoading.value) {
    return message.warning("AI扩写生成中请耐心等待");
  }
  addTitledrawer.value.showDrawer(openType);

  console.log(titleList.value, "titleList.value 标题数组");
};

const addTitleSuccess = (info) => {
  titleList.value = info;

  console.log(titleList.value, "标题的数据格式");
};

const anchorTypeListComputed = computed(() => {
  return [
    {
      label: "无",
      value: 0,
      disabled: false,
    },
    {
      label: "位置",
      value: 1,
      disabled: false,
    },
  ];
  if (douyinQrcode.value) {
    return [
      {
        label: "无",
        value: 0,
        disabled: false,
      },
      {
        label: "位置",
        value: 1,
        disabled: false,
      },
    ];
  } else {
    return [
      {
        label: "无",
        value: 0,
        disabled: false,
      },

      {
        label: "抖音小程序",
        value: 2,
        disabled: false,
      },
      {
        label: "抖音小黄车",
        value: 3,
        disabled: false,
      },
    ];
  }
});

const input_value = ref("可输入")

// 添加位置
const addpoilist = ref(null);
const borderErrStyle = ref(false);
const addPoiHandle = () => {
  borderErrStyle.value = false;
  addpoilist.value.showDrawer();
};

// 删除某项挂载位置
const deletePoiList = (id) => {
  const index = poiList.value.findIndex((ele) => ele.id == id);
  if (index != -1) {
    poiList.value.splice(index, 1);
  }

  console.log(poiList.value, "删除后的数组长什么样");
};

// 选择项目
const poiId = ref([]);
const visibleStorePOI = ref(false);
const storePOI = () => {
  if (poiList.value.length) {
    poiId.value = poiList.value.map((item) => item.id);
  } else {
    poiId.value = [];
  }
  visibleStorePOI.value = true;
};

// 位置添加成功
const addPoiSuccess = (info) => {
  const uniqueById = info.reduce((acc, current) => {
    if (!acc[current.id]) {
      acc[current.id] = current;
    }
    return acc;
  }, {});

  poiList.value = Object.values(uniqueById);

  console.log(poiList.value, "去重");
};

const onConfirmStorePOI = (list) => {
  poiList.value = list;
  visibleStorePOI.value = false;
};

const ResizableWidth = ref(80);
const Resizableheight = ref(80);
const ResizableActive = ref(false);
const editSubtitleItem = ref({
  x: 10,
  y: 10,
  subtitle_id: "1",
});

// 拖动结束修改 x和y的位置
const dragEndHandle = (data) => {
  console.log("拖拽结束", data);
  console.log(ResizableWidth.value, "二维码的长度");
  console.log(Resizableheight.value, "二维码的宽度");
};

// 加载图片尺寸的方法
const imageWidth = ref(0);
const imageHeight = ref(0);
const targetWidth = ref(226);
const loadImageDimensions = async (url) => {
  return new Promise((resolve, reject) => {
    const image = new Image();

    // 当图像加载成功时触发
    image.onload = () => {
      if (image.width <= targetWidth.value) {
        imageWidth.value = image.width;
        imageHeight.value = image.height;
      } else {
        const aspectRatio = image.width / image.height;
        const newHeight = targetWidth.value / aspectRatio;
        imageWidth.value = 226;
        imageHeight.value = Math.round(newHeight);
      }
      resolve({ width: imageWidth.value, height: imageHeight.value });
    };

    // 如果图像加载失败，则返回错误信息
    image.onerror = () => {
      reject(new Error("无法加载图片"));
    };
    image.src = url;
  });
};

// 计算容器样式
const containerStyle = computed(() => ({
  width: `${imageWidth.value}px`,
  height: `${imageHeight.value}px`,
  backgroundColor: "pink",
}));

watch(
  () => imageUrl.value,
  (val) => {
    if (val) {
      // 使用示例
      loadImageDimensions(val);
    }
  },
  {
    immediate: true,
  }
);

const submitFn = () => {
  validate().then(() => {
    if (modelRef.value.anchor_type == 1 && poiList.value.length == 0) {
       return message.error("请添加位置");
    }
    // if (modelRef.value.poster == "") {
    //   return message.error("请上传活动扫码海报");
    // }
    let arr_materials = [];
    modelRef.value.intoPieces.forEach((item) => {
      let material_id = item?.material_id ?? 0;
      let param_materials = {};
      if (material_id > 0) {
        param_materials["id"] = item.id;
        param_materials["material_id"] = material_id;
      } else {
        param_materials["material_id"] = item.id;
      }
      param_materials["material_url"] = item.material_url;
      arr_materials.push(param_materials);
    });
    let arrdescs = [];

    console.log(titleList.value,   '描述相关 要加一个字段');
    titleList.value.forEach((item) => {
      arrdescs.push({
        des: item.caption,
        hashtag_name: item.hashtag_name
      });
    });
    let arrstore = [];
    poiList.value.forEach((item) => {
      arrstore.push(item.id);
    });

    let params = {
      name: modelRef.value.name,
      // poster: modelRef.value.poster,
      end_time: dayjs(modelRef.value.end_time).format("YYYY-MM-DD HH:mm:ss"),
      materials: arr_materials,
      descs: arrdescs,
      store: arrstore,
    };
    if (activity_id.value > 0) {
      params["id"] = activity_id.value;
      request
        .put("/work_ai", "/hotStore/activity/update", params)
        .then((res) => {
          if (res.result) {
            message.success("编辑成功!");
            goback();
          }
        })
        .catch((err) => {
          message.success("编辑失败,请重试");
        });
    } else {
      request
        .post("/work_ai", "/hotStore/activity/add", params)
        .then((res) => {
          if (res.result) {
            message.success("添加成功!");
            goback();
          }
        })
        .catch((err) => {
          message.success("添加失败,请重试");
        });
    }
  });
};

const debouncedsubmitFn = debounce(submitFn, 1000, {
  leading: true,
  trailing: false,
});

// 编辑
const getInfo = (id) => {
  let params = {
    id: id,
  };
  if (id > 0) {
    activity_id.value = id;
  } else {
    activity_id.value = 0;
  }

  request
    .get("/work_ai", "/hotStore/activity/get", params)
    .then((res) => {
      modelRef.value.name = res.result.name;
      modelRef.value.end_time = res.result.end_time;
      // modelRef.value.poster = res.result.poster;

      console.log(res,   '编辑请求的数据11111');
      res.result.videos.forEach((item) => {
        filmVideoList.value.push({
          id: item.id,
          material_id: item.material_id,
          org_id: item.org_id,
          material_name: item.material_name,
          material_type: item.material_type,
          material_url: item.material_url,
          material_duration: 2500,
          cover_url: item.cover_thumb,
        });
      });
      modelRef.value.intoPieces = filmVideoList.value;

      res.result.descs.forEach((item) => {
        titleList.value.push({
          caption: item.des,
          hashtag_name: item.hashtag_name,
        });
      });

      if (res.result.mount_info) {
        if (res.result.mount_info.length == 0) {
          modelRef.value.anchor_type = 0;
        } else {
          modelRef.value.anchor_type = 1;
        }
      }


      res.result.mount_info.forEach((item) => {
        poiList.value.push({
          id: item.id,
          store_name: item.name,
          poi_id: item.poi_id,
        });
      });
    })
    .catch((err) => {});
};

// 处理时间变化的函数
const handleTimeChange = (value) => {
  const now = new Date();
  const halfHourLater = new Date(now.getTime() + 30 * 60 * 1000);
  const selectedTime = value ? new Date(value) : null;

  if (selectedTime && selectedTime < halfHourLater) {
    message.error("请选择正确时间")
    modelRef.value.end_time = null; 
  } 
};

const RestoreFn = () => {
  modelRef.value.poster =
    "https://shotstack.oss-cn-hangzhou.aliyuncs.com/upload/shotstack/20241112/t9kuWMhcuRjEaqgKvv5JV.jpg";
  message.success("已恢复初始图");
};

watch(
  () => route.query.id,
  (val) => {
    if (val) {
      getInfo(val);
    } else {
      activity_id.value = 0;
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped>
.bd-r {
  border-radius: 5px;
}

.content_box {
  display: flex;
  width: 100%;
  height: 100%;
  margin-top: 20px;
  .contemt_left {
    width: 100%;

    .content_left_top {
      width: 100%;
      border-radius: 4px;
      background-color: #fff;
      padding: 20px;
      padding-right: 40%;
      height: 200px;
    }

    .content_left_bottom {
      width: 100%;
      margin-top: 20px;
      border-radius: 4px;
      background-color: #fff;
      padding: 20px;
      padding-right: 40%;
      // height: 70%;
    }
  }
  .contemt_right {
    margin-left: 10px;
    width: 50%;
    .top_content {
      background-color: #fff;
      border-radius: 4px;
      padding: 20px;
      display: flex;
      height: 560px;
    }

    .phone {
      width: 260px;
      height: 520px;
      margin-left: 20px;
      position: relative;
      .one_content {
        background-color: #edeefc;
        width: 226px;
        height: 408px;
        border: 1px solid #e5e5e5;
        position: absolute;
        top: 49px;
        left: 18px;

        .top_header {
          width: 100%;
          height: 40px;
          padding: 0 10px;
          background-color: #fff;
          display: flex;
          align-items: center;
          .right {
            margin-left: 22%;
          }
        }

        .content_img {
          width: 100%;
          height: 368px;
          position: relative;
          .content_img_img {
            width: 100%;
            display: inline-block;
          }

          .new_content_code {
            width: 80px;
            height: 80px;
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
          }
        }

        .content_code {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}

.bottom_btn {
  // margin-top: 20px;
  display: flex;
  flex-direction: row-reverse;
  padding-right: 40%;

  .bd-r {
    margin-left: 10px;
  }
}
.info_text {
  color: #999;
  font-size: 12px;
  margin-top: 10px;
}

.up_box {
  display: flex;
  align-items: flex-end;
  position: relative;
  .Rup_btn {
    border-radius: 5px;
    margin: 0 0 8px 5px;
  }

  .example {
    position: absolute;
    text-align: center;
    background: rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    margin-bottom: 20px;
    padding: 48px 197px;
    margin: 0px -6px;
    z-index: 99999 !important;
  }
}

.ss-upload-picture-card-wrapper {
  width: 109px !important;
}

.movieslist {
  display: flex;
  flex-wrap: wrap;
  grid-template-columns: repeat(5, 1fr); //平分5等份
  grid-gap: 16px;
  max-height: 232px;
  overflow: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  // 添加成片
  .movies_add {
    width: 100px;
    border: 1px solid #e0e0e6;
    border-radius: 5px;
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgb(236, 236, 236);
    cursor: pointer;
  }

  .movies_item {
    width: 100px;
    border: 1px solid #e0e0e6;
    border-radius: 5px;
    height: 100px;
    background-color: rgb(236, 236, 236);
    position: relative;

    // 持续时长
    .movies_duration {
      position: absolute;
      bottom: 2px;
      left: 2px;
      width: 40px;
      border-radius: 5px;
      color: #fff;
      // z-index: 999;
      background: #494949;
      text-align: center;
      font-size: 10px;
    }

    // 播放按钮
    .movies_itemmask {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 0;
      left: 0;
      visibility: hidden;
      background-color: rgba(0, 0, 0, 0.5);

      .play_icon {
        margin-top: 50%;
        margin-left: 50%;
        transform: translate(-50%, -50%);

        &:hover {
          color: var(--ss-primary-color) !important;
        }
      }

      .movies_closebtn {
        margin-top: 100%;
        margin-left: 85px;
        color: #fff;
        // &:hover {
        //   color: var(--ss-primary-color);
        // }
      }
    }

    &:hover .movies_itemmask {
      visibility: visible;
    }
  }
}

.title_tip {
  display: flex;
  justify-content: space-between;
  height: 30px;
  cursor: pointer;

  :deep(.ss-btn[disabled]) {
    display: flex !important;
  }
}

.title_list_one {
  border: 1px solid #e0e0e6;
  border-radius: 5px;
  background-color: #fff;
}

.title_list_more {
  width: 100%;
  max-height: 240px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 8px;
    /* 滚动条的宽度 */
    height: 10px;
    /* 滚动条的高度，垂直滚动条可能用得上 */
    display: none;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    /* 滑块的背景颜色 */
    border-radius: 10px;
    /* 滑块的圆角 */
  }

  .title-item {
    width: 100%;
    border: 1px solid #e0e0e6;
    margin-top: 10px;
    border-radius: 5px;
    cursor: pointer;
    .item-text {
      padding: 10px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .item-caption {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 35px;
      padding: 10px;

      .caption {
        flex: 1;
        white-space: nowrap;
        /* 防止文字换行 */
        overflow: hidden;
        /* 隐藏溢出的内容 */
        text-overflow: ellipsis;
        /* 使用省略号表示溢出的文本 */
      }

      .operation {
        visibility: hidden;
        margin-left: 5px;
        cursor: pointer;
        .edit_btn,
        .delete_btn {
          &:hover {
            color: var(--ss-primary-color);
          }
        }
      }
    }

    .hashtag_name {
      padding: 5px;
    }
    &:hover .operation {
      visibility: visible;
    }
  }
}

:deep(textarea) {
  &::-webkit-scrollbar {
    width: 3px;
  }
}

// 去除校验失败边框颜色
:deep(
    .ss-form-item-has-error
      .ss-select:not(.ss-select-disabled):not(.ss-select-customize-input)
      .ss-select-selector
  ) {
  border-color: #fff !important;
}

:deep(.ss-form-item-explain-error) {
  padding-left: 10px !important;
}

.textarea {
  &::-webkit-scrollbar {
    display: none;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
}

:deep(.ss-select-multiple .ss-select-selection-item) {
  background: #d5e3f4 !important;
}

.see_posion {
  height: 100%;
  border-radius: 5px;
  margin-right: 3px;
  background-color: var(--ss-primary-color);
  color: #fff;
  padding: 0 5px;
}

.fz12 {
  font-size: 12px;
}

.img_haibao {
  width: 70px;
  height: 90px;
}

.position_box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .position_box_item {
    cursor: pointer;
    margin-bottom: 10px;
    border-radius: 4px;
    margin-right: 10px;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #096dd9;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2px 4px;
    .del_icon {
      font-size: 10px;
      margin-left: 5px;
    }
  }
}
</style>
